package router

import (
	"fmt"
	"gitee.com/baizhige/go-server-tempalte/common/config"
	"gitee.com/baizhige/go-server-tempalte/common/log"
	"gitee.com/baizhige/mongong-go"
	"gitee.com/baizhige/mongong-go/query"
	"github.com/gin-gonic/gin"
)

func init() {
	//gin.SetMode(gin.ReleaseMode)
	engin = gin.Default()
}
func ListenWeb(port int, r func(gin.IRouter)) {

	//全局中间件
	engin.Use(ResultReceiveMiddleware) //全局统一异常处理、结果封装
	//engin.Use(CommonMiddleware)        //通用中间件

	//注册路由
	r(engin)

	//异步初始化路由到库和缓存中
	go InitRouters()

	//启动监听
	engin.Run(fmt.Sprintf(":%v", port))
}

func InitRouters() {
	routes := engin.Routes()
	// 初始化容器
	Container = make(map[string]*Router, len(routes))

	for _, routeInfo := range routes {
		projectName := config.Project.App.Name
		method := routeInfo.Method
		path := routeInfo.Path

		//构建查询条件
		filter := query.
			Eq("project", projectName).
			Eq("method", method).
			Eq("path", path)

		repository := mongong.Coll[Router]()
		apiRoute, err := repository.QueryOne(filter)
		if err != nil {
			//说明需要初始化到库里
			apiRoute = newRoute(projectName, method, path)
			_, err = repository.InsertOne(apiRoute) //入库
			if err != nil {
				log.ErrorF("router init fail :%v", err)
			}
		}
		key := method + "_" + path
		Container[key] = apiRoute
	}

}

func Get(method, path string) (*Router, bool) {
	router, ok := Container[method+"_"+path]
	return router, ok
}

func Refresh(r *Router) {
	key := r.Method + "_" + r.Path
	Container[key] = r
}

func Clear(r *Router) {
	key := r.Method + "_" + r.Path
	delete(Container, key)
}

func newRoute(projectName, method, path string) *Router {
	return &Router{
		Id:        projectName + ":" + method + ":" + path,
		Name:      "",
		Project:   projectName,
		Path:      path,
		Method:    method,
		NeedLogin: false,
		NeedAuth:  false, //默认不
		Enable:    true,
		ReqDec:    false,
		RespEnc:   false,
		LogConfig: &LogConfig{
			InDb:     false,
			ReqPrint: true, //默认打印
			ResPrint: true, //默认打印
		},
	}
}
